//store必须是一个函数的形式,不然没有作用域的限制会产生模块件变量混乱的问题
const state = () => ({
  userInfo: null, //用户信息对象
  accessToken: null, //访问令牌字符串
  refreshToken: null //刷新令牌字符串
});

const mutations = {
  //重置用户状态
  RESET_USER_STATE(state) {
    state.userInfo = null; //用户信息对象
    state.accessToken = null; //访问令牌字符串
    state.refreshToken = null; //刷新令牌字符串
  },
  //刷新页面后，重新更新状态
  UPDATE_ALL_STATE(state, data) {
    state.userInfo = data.userInfo;
    state.accessToken = data.accessToken;
    state.refreshToken = data.refreshToken;
  }
};

const actions = {
  //第一个参数可接受{commit,state},第二个参数是context上下文对象
  nuxtServerInit({ commit }, { app }) {
    const data = {};
    data.userInfo = app.$cookies.get("userInfo");
    data.accessToken = app.$cookies.get("accessToken");
    data.refreshToken = app.$cookies.get("refreshToken");
    data.redirectURL = app.$cookies.get("redirectURL");
    commit("UPDATE_ALL_STATE", data);
  },

  //跳转登录页
  LoginPage({ commit }) {
    //登录前先重置用户状态
    commit("RESET_USER_STATE");
    //跳转登录页，redirectURL引发跳转到登录页的URL
    //LoginPage只能在客户端进行调用，因为只有客户端才有window对象
    window.location.href = `${process.env.authURL}?redirectURL=${window.location.href}`;
  },
  // 退出, 将用户状态值清空
  UserLogout({ commit }) {
    // 重置状态
    commit("RESET_USER_STATE");
    window.location.href = `${process.env.authURL}/logout?redirectURL=${window.location.href}`;
  }
};
export default {
  state,
  mutations,
  actions
};
